﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Bangle.SerialPort
{
    public static class Extentions
    {
        public static IServiceCollection AddSerialPort(this IServiceCollection services, IConfiguration configuration)
        {
            var types = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(a => a.GetTypes()
                        .Where(t =>
                            t.GetInterfaces().Contains(typeof(ISerialPortService))
                            && !t.IsAbstract
                        ))
                        .ToArray();

            foreach (var type in types)
            {
                services.AddScoped(type, type);
                var attr = type.GetCustomAttribute<SerialPortAttribute>();

                SerialPortFactory.Add(attr.Name, type);
            }

            services.AddScoped<SerialPortFactory, SerialPortFactory>();
            services.AddScoped<ISerialPortSender, SerialPortSender>();
            return services;
        }
    }


}